//
//  ContactsViewController.m
//  聊吧
//
//  Created by 刘洋 on 16/6/13.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "ContactsViewController.h"
#import "AddFriendViewController.h"
#import "NewFriendViewController.h"
#import "TopListTableViewCell.h"
#import "ChattingViewController.h"
#import "ContactsTableVewCell.h"

static NSString *contactsCell = @"contactsCell";
static NSString *topListCell = @"topListCell";

@interface ContactsViewController ()<UITableViewDelegate,UITableViewDataSource,EMChatManagerDelegate>

@property(nonatomic,retain)BaseTableView *contactsTableView;
@property(nonatomic,retain)NSMutableArray *friendsList;
@property(nonatomic,retain)NSMutableDictionary *friendDic;
@property(nonatomic,retain)NSMutableArray *firstLetterArray;


@end

@implementation ContactsViewController

-(void)dealloc{
    [_contactsTableView release];
    [_friendsList release];
    [_friendDic release];
    [super dealloc];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    self.friendDic = [NSMutableDictionary dictionary];

    
    //从服务器上获取好友数组
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        
        if (!error) {

            [self.friendsList removeAllObjects];
            [self.friendsList addObjectsFromArray:buddyList];
            
            
            for (EMBuddy *buddy in self.friendsList) {
                char letter = [ChineseToPinyin sortSectionTitle:buddy.username];
 
                NSString *letterString = [NSString stringWithFormat:@"%c",letter];

                NSMutableArray *nameArray = [NSMutableArray array];
       
                [self.friendDic setObject:nameArray forKey:letterString];
                
          
                }
            
           
            
            // 1.遍历所有名
            // 2.取出所有名首字母
            // 3.根据首字母取出空数组
            // 4.直接将姓名addobjec到空数组里
            

            for (EMBuddy *buddy in self.friendsList) {
                char first = [ChineseToPinyin sortSectionTitle:buddy.username];
                NSString *firstString = [NSString stringWithFormat:@"%c",first];
                
                NSMutableArray *array = [self.friendDic objectForKey:firstString];
                [array addObject:buddy.username];
          
            }
            
            NSLog(@"%@",self.friendDic);
     
            [self.contactsTableView reloadData];
        }
        
    } onQueue:dispatch_get_main_queue()];
    
    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
     [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"联系人";
    
    self.friendsList = [NSMutableArray array];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"contacts_add_friend"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(addFriendButton)];
    
    
    self.contactsTableView = [[BaseTableView alloc]initWithFrame:CGRectMake(0, 0, ROOTWIDTH, ROOTHEIGHT - naVCHeight - tabBarHeight) style:UITableViewStylePlain];
    self.contactsTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contactsTableView];
    [_contactsTableView release];
    
    self.contactsTableView.delegate = self;
    self.contactsTableView.dataSource = self;
    
    
    self.contactsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contactsTableView registerClass:[ContactsTableVewCell class] forCellReuseIdentifier:contactsCell];
     [self.contactsTableView registerClass:[TopListTableViewCell class] forCellReuseIdentifier:topListCell];
    
    
    // Do any additional setup after loading the view.
}

#pragma mark -- 添加好友按钮
-(void)addFriendButton{
    
    AddFriendViewController *addVC = [[AddFriendViewController alloc]init];
    addVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:addVC animated:YES];
    [addVC release];
    
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSArray *sectionKey = [self SortFirstLetter:self.friendDic];
    
    return sectionKey.count + 1 ;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        NSArray *sectionKey = [self SortFirstLetter:self.friendDic];
        NSString *key = sectionKey[section - 1];
        NSArray *tempArray = [self.friendDic objectForKey:key];
        return tempArray.count;
        
        
        
        
    }
    
   
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
 
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (indexPath.section == 0) {
        
        TopListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:topListCell];

        switch (indexPath.row) {
            case 0:
                cell.titleLabel.text = @"新的朋友";
                cell.titleImage.image = [UIImage imageNamed:@"plugins_FriendNotify"];
                 NSMutableDictionary *dic = [AppDelegate shareFriendDic];
                if (dic.count == 0) {
                    cell.newCounts.hidden = YES;
                }else{
                    cell.newCounts.hidden = NO;
                    cell.newCounts.text = [NSString stringWithFormat:@"%ld",dic.count];
                }
                
                break;
       /*
            case 1:
                cell.titleLabel.text = @"群组";
                 cell.titleImage.image = [UIImage imageNamed:@"add_friend_icon_addgroup"];
                break;
            case 2:
                cell.titleLabel.text = @"讨论组";
                 cell.titleImage.image = [UIImage imageNamed:@"add_friend_icon_offical"];
                break;
        */
          
            default:
                break;
        }
        
        return cell;
        
        
        
    }else{
   
    ContactsTableVewCell *cell = [tableView dequeueReusableCellWithIdentifier:contactsCell];
        
    
        NSArray *sectionKey = [self SortFirstLetter:self.friendDic];
        NSArray *tempValue = [self.friendDic objectForKey:sectionKey[indexPath.section - 1]];
        cell.nameLabel.text = [tempValue objectAtIndex:indexPath.row];
       
         return cell;
    }
   
    

}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        NewFriendViewController *newVC = [[NewFriendViewController alloc]init];
        newVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newVC animated:YES];
        [newVC release];
    }
    if (indexPath.section != 0) {
        NSArray *array = [self SortFirstLetter:self.friendDic];
        NSArray *tempArr = [self.friendDic objectForKey:array[indexPath.section - 1]];
        NSString *name = tempArr[indexPath.row];
        
        ChattingViewController *chattingVC = [[ChattingViewController alloc]init];
        chattingVC.oppositeName = name;
        
        chattingVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:chattingVC animated:YES];
        [chattingVC release];
    }
   
    
    
}


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    NSArray *array = [self SortFirstLetter:self.friendDic];
    
    if (section == 0) {
        
        return @"新的朋友";
    }else{
        
        return array[section - 1];
    }
    
    
}


//索引
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    return [self SortFirstLetter:self.friendDic]; //调用排序方法
}





//封装  对通讯录分区首字母排序的方法
-(NSArray *)SortFirstLetter:(NSMutableDictionary *)dic{
    NSArray *arr = [dic allKeys];
    NSSortDescriptor *sortDes = [[NSSortDescriptor alloc]initWithKey:@"self" ascending:YES];
    NSArray *newArr = [arr sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortDes, nil]];
    return newArr;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section != 0) {
        return YES;
    }else{
        return NO;
    }
    
  
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
    
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSMutableArray *array = [NSMutableArray arrayWithArray: [self SortFirstLetter:self.friendDic]];
    NSMutableArray *tempArr = [self.friendDic objectForKey:array[indexPath.section - 1]];
    NSString *name = tempArr[indexPath.row];
    
    [[EaseMob sharedInstance].chatManager removeBuddy:name removeFromRemote:YES error:nil];
    
    [tempArr removeObjectAtIndex:indexPath.row];
    
    if (tempArr.count == 0) {
        
      //  [array removeObjectAtIndex:indexPath.section - 1];
        [self.friendDic removeObjectForKey:@"name"];
    }
    
             [self.contactsTableView reloadData];

    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
